import { getEnv, getAccountInfoSync, showToast, hideLoading, getStorageSync } from '@tarojs/taro';
import { CONTENT_TYPE, ERROR_MSG_DURATION, Prefix } from '@/constants';
import { useAuthStore } from '@/store';
import { useRouterPush } from '@/composables';
import { localStg, exeStrategyActions } from '@/utils';
const env = getEnv();

/**
 * 获取请求路径
 * @param url
 */
export function getRequestUrl(url: string) {
  let baseUrl = '';
  const actions: Common.StrategyAction[] = [
    [env === 'WEB', () => (baseUrl = `/${Prefix}${url}`)],
    [
      env === 'WEAPP',
      () => {
        const { miniProgram } = getAccountInfoSync();
        const hosts = {
          // develop: 'http://192.168.10.87:8080/jeecg-boot', // 开发
          // trial: 'http://192.168.10.87:8080/jeecg-boot', // 开发

          develop: 'https://anfine.huasun-healthcare.com/' + Prefix, // 开发
          trial: 'https://anfine.huasun-healthcare.com/' + Prefix, // 体验
  
          release: 'https://anfine.huasun-healthcare.com/' + Prefix // 正式
        };
        baseUrl = url.substring(0, 1) === '/' ? `${hosts[miniProgram.envVersion]}${url}` : `${url}`;
      }
    ],
    [
      true,
      () => {
        baseUrl = url.substring(0, 1) === '/' ? `${process.env.HTTP_URL}${url}` : `${url}`;
      }
    ]
  ];
  exeStrategyActions(actions);

  return baseUrl;
}

/** 获取请求头 */
export function getRequestHeaders(axiosConfig: Service.AxiosConfig) {
  const header: TaroGeneral.IAnyObject = {};
  /** 获取token */
  const token = localStg.get('token');
  if (token) {
    /** 添加token */
    // header.Authorization = token;
    header['X-Access-Token'] = token;
  }
  
  // 优先从 nurse_user 中获取 defaultHospital，为空时使用默认值 A01A03A01
  const nurseUser = localStg.get('nurseUser');
  let sys_org_code = 'A01A03A01'; // 默认值
  
  if (nurseUser?.defaultHospital) {
    // defaultHospital 对应 nurse_hospital 的 id，需要获取对应的 sys_org_code
    const defaultHospital = getStorageSync('defaultHospital');
    if (defaultHospital) {
      try {
        const hospitalInfo = JSON.parse(defaultHospital);
        if (hospitalInfo.sysOrgCode) {
          sys_org_code = hospitalInfo.sysOrgCode;
        }
      } catch (e) {
        console.error('解析医院信息失败:', e);
      }
    }
  } else {
    // 如果 nurse_user 中没有 defaultHospital，则尝试从 localStorage 获取
    sys_org_code = localStg.get('sys_org_code') || 'A01A03A01';
  }
  
  if (sys_org_code) {
    header['sys_org_code'] = sys_org_code;
  }
  
  /** 增加类型 */
  header['Content-Type'] = axiosConfig.contentType || CONTENT_TYPE.json;
  return header;
}

/** token过期处理 */
export function handleExpireToken() {
  const { resetAuthStore } = useAuthStore();
  const { toLogin } = useRouterPush();

  // 隐藏加载状态
  hideLoading();

  // 显示提示信息
  showToast({
    title: 'Token失效，请重新登录!',
    icon: 'none',
    duration: 2000
  });
  return

  // 清除用户信息
  resetAuthStore();

  // 延迟跳转到登录页面，让用户看到提示信息
  setTimeout(() => {
    toLogin();
  }, 2000);

  return null;
}

export function showErrorMsg(message: string) {
  hideLoading();

  showToast({
    title: message,
    icon: 'none',
    duration: ERROR_MSG_DURATION
  });
}
